<template>
    <div class="lottery-list-container">
        <div class="page-header">
            <h2>抽奖活动管理 <el-tag v-if="autoRefresh" type="success" size="small">自动刷新中</el-tag></h2>
            <div class="header-actions">
                <el-switch v-model="autoRefresh" active-text="自动刷新" inactive-text="手动刷新"
                    @change="handleAutoRefreshChange" />
                <el-button type="primary" :icon="Plus" @click="goToCreate">创建抽奖</el-button>
                <el-button type="info" :icon="Refresh" @click="fetchLotteryList">刷新</el-button>
            </div>
        </div>

        <!-- 搜索和筛选区域 -->
        <div class="search-area">
            <!-- 搜索和筛选选项 -->
        </div>

        <!-- 列表区域 -->
        <el-table :data="lotteryList" v-loading="loading" style="width: 100%">
            <!-- 表格列定义 -->
            <el-table-column prop="_id" label="活动ID" width="220" />
            <el-table-column prop="title" label="活动名称" min-width="120" />
            <!-- 确保列中显示参与人数 -->
            <el-table-column prop="participantsCount" label="参与人数" align="center" width="120">
                <template #default="scope">
                    <span :class="{ 'highlight-change': scope.row.participantsChanged }">
                        {{ scope.row.participantsCount || 0 }}/{{ scope.row.maxParticipants }}
                    </span>
                </template>
            </el-table-column>

            <!-- 添加频道要求列 -->
            <el-table-column prop="requireChannel" label="频道要求" width="120">
                <template #default="scope">
                    <el-tag v-if="scope.row.requireChannel" type="success" size="small">
                        需关注频道
                    </el-tag>
                    <el-tag v-else type="info" size="small">无要求</el-tag>
                </template>
            </el-table-column>

            <!-- 其他列 -->

            <!-- 操作列 -->
            <el-table-column label="操作" width="200" fixed="right">
                <template #default="scope">
                    <el-button type="primary" link @click="viewLotteryDetail(scope.row._id)">
                        查看详情
                    </el-button>
                    <el-button v-if="scope.row.status === 'active'" type="success" size="small"
                        @click="handleDraw(scope.row._id)">
                        开奖
                    </el-button>
                    <el-button v-if="scope.row.status === 'pending'" type="danger" size="small"
                        @click="handleCancel(scope.row._id)">
                        取消
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-container">
            <el-pagination class="pagination" background :current-page="pagination.current"
                :page-size="pagination.pageSize" :page-sizes="[10, 20, 30, 50]"
                layout="total, sizes, prev, pager, next, jumper" :total="pagination.total"
                @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>
    </div>
</template>

<script>
import { ref, reactive, onMounted, onBeforeUnmount } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus, Refresh } from '@element-plus/icons-vue';
import { getLotteryList, cancelLottery, drawLottery } from '../../../api/lottery';

export default {
    name: 'LotteryList',
    setup() {
        const router = useRouter();

        const loading = ref(false);
        const lotteryList = ref([]);
        const currentPage = ref(1);
        const pageSize = ref(10);
        const total = ref(0);
        const autoRefresh = ref(true);
        let refreshTimer = null;
        let highlightTimer = null;
        const lastFetchTime = ref(0);

        // 获取抽奖列表
        const fetchLotteryList = async () => {
            loading.value = true;
            try {
                const res = await getLotteryList({
                    page: currentPage.value,
                    limit: pageSize.value
                });

                if (res.success) {
                    lotteryList.value = res.data.list;
                    total.value = res.data.pagination.total;
                    currentPage.value = res.data.pagination.current;
                    pageSize.value = res.data.pagination.pageSize;
                    lastFetchTime.value = Date.now();

                    // 如果启用自动刷新，确保定时器正常工作
                    if (autoRefresh.value) {
                        startAutoRefresh();
                    }

                    // 设置定时器，3秒后清除高亮状态
                    highlightTimer = setTimeout(() => {
                        lotteryList.value = lotteryList.value.map(item => ({
                            ...item,
                            participantsChanged: false
                        }));
                    }, 3000);
                } else {
                    ElMessage.error(res.message || '获取抽奖列表失败');
                }
            } catch (error) {
                console.error('获取抽奖列表失败:', error);
                ElMessage.error('获取抽奖列表失败');
            } finally {
                loading.value = false;
            }
        };

        // 开始自动刷新
        const startAutoRefresh = () => {
            stopAutoRefresh(); // 先停止现有的定时器

            if (autoRefresh.value) {
                refreshTimer = setInterval(fetchLotteryList, 10000); // 每10秒刷新一次，提高实时性
                console.log('已启动抽奖列表自动刷新 (10秒间隔)');
            }
        };

        // 停止自动刷新
        const stopAutoRefresh = () => {
            if (refreshTimer) {
                clearInterval(refreshTimer);
                refreshTimer = null;
            }
        };

        // 处理自动刷新开关变化
        const handleAutoRefreshChange = (val) => {
            if (val) {
                startAutoRefresh();
                ElMessage.success('已开启自动刷新');
            } else {
                stopAutoRefresh();
                ElMessage.info('已关闭自动刷新');
            }
        };

        // 分页处理
        const handleSizeChange = (val) => {
            pageSize.value = val;
            fetchLotteryList();
        };

        const handleCurrentChange = (val) => {
            currentPage.value = val;
            fetchLotteryList();
        };

        // 查看详情
        const viewLotteryDetail = (id) => {
            router.push(`/admin/points/lottery/${id}`);
        };

        // 跳转到创建页面
        const goToCreate = () => {
            router.push('/admin/points/lottery/create');
        };

        // 取消抽奖
        const handleCancel = async (id) => {
            try {
                await ElMessageBox.confirm('确定要取消此抽奖活动吗？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                });

                const res = await cancelLottery(id);
                if (res.data && res.data.success) {
                    ElMessage.success('抽奖活动已取消');
                    fetchLotteryList();
                } else {
                    ElMessage.error(res.data.message || '取消抽奖活动失败');
                }
            } catch (error) {
                if (error !== 'cancel') {
                    console.error('取消抽奖活动失败:', error);
                    ElMessage.error('取消抽奖活动失败');
                }
            }
        };

        // 手动开奖
        const handleDraw = async (id) => {
            try {
                await ElMessageBox.confirm('确定要立即开奖吗？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                });

                const res = await drawLottery(id);
                if (res.data && res.data.success) {
                    ElMessage.success('抽奖活动已开奖');
                    fetchLotteryList();
                } else {
                    ElMessage.error(res.data.message || '开奖失败');
                }
            } catch (error) {
                if (error !== 'cancel') {
                    console.error('开奖失败:', error);
                    ElMessage.error('开奖失败');
                }
            }
        };

        // 组件挂载时获取数据并启动自动刷新
        onMounted(() => {
            fetchLotteryList();
            startAutoRefresh();
        });

        // 组件卸载前清除定时器
        onBeforeUnmount(() => {
            stopAutoRefresh();
            if (highlightTimer) {
                clearTimeout(highlightTimer);
                highlightTimer = null;
            }
        });

        return {
            Plus,
            Refresh,
            loading,
            lotteryList,
            currentPage,
            pageSize,
            total,
            autoRefresh,
            fetchLotteryList,
            handleSizeChange,
            handleCurrentChange,
            viewLotteryDetail,
            goToCreate,
            handleCancel,
            handleDraw,
            handleAutoRefreshChange
        };
    }
}
</script>

<style scoped>
.lottery-list-container {
    padding: 20px;
}

.page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
}

.page-header h2 {
    margin: 0;
    display: flex;
    align-items: center;
    gap: 8px;
}

.header-actions {
    display: flex;
    gap: 12px;
    align-items: center;
}

.search-area {
    margin-bottom: 20px;
    padding: 16px;
    background-color: #f5f7fa;
    border-radius: 4px;
}

.pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
}

.highlight-change {
    background-color: #ecf5ff;
    padding: 2px 6px;
    border-radius: 4px;
    animation: highlight-fade 3s;
    font-weight: bold;
}

@keyframes highlight-fade {
    0% {
        background-color: #ecf5ff;
    }

    50% {
        background-color: #d9ecff;
    }

    100% {
        background-color: transparent;
    }
}
</style>